const STORAGE_POOL: Record<string, Ref<any>> = {};

function initStorage<T>(key: string, defaultValue: T) {
  const storageValue = uni.getStorageSync(key);

  // 使用类型安全的方式处理存储值
  const initialValue =
    storageValue !== "" && storageValue !== null && storageValue !== undefined
      ? (storageValue as T)
      : defaultValue;

  // 确保存储有值
  if (storageValue === "" || storageValue === null || storageValue === undefined) {
    uni.setStorageSync(key, defaultValue);
  }

  const storageRef = ref<T>(initialValue);
  STORAGE_POOL[key] = storageRef;

  watch(
    () => storageRef.value,
    (newValue) => {
      uni.setStorageSync(key, newValue);
    }
  );
}

export function useStorage<T = string>(key: string, defaultValue?: T) {
  // 根据泛型类型处理默认值
  const initialValue = defaultValue !== undefined ? defaultValue : ("" as unknown as T);

  if (!STORAGE_POOL[key]) {
    initStorage<T>(key, initialValue);
  }

  // 添加类型断言确保返回类型正确
  return STORAGE_POOL[key] as Ref<T>;
}
